//
//  CoreDateManager.m
//  SQLiteTest
//
//  Created by rhljiayou on 14-1-8.
//  Copyright (c) 2014年 rhljiayou. All rights reserved.
//

#import "CoreDateManager.h"
#import "HomeData.h"
#import "HomeModel.h"
#import "MJExtension.h"
#import "BPProducts.h"
#import "BPProductDetail.h"
#import "PagedetailData.h"
#import "Address.h"
#import "MyProducts.h"
#import "BPProductModel.h"
#import "BPProductDetailPage.h"
#import "ListData.h"
#import "productModel.h"
#import "UnpostArry.h"
#import "ZBpostModel.h"
#import "MBProgressHUD+MJ.h"

@implementation CoreDateManager

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (void)saveContext
{
    NSError *error = nil;
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            BPLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

#pragma mark - Core Data stack

- (NSManagedObjectContext *)managedObjectContext
{
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        _managedObjectContext = [[NSManagedObjectContext alloc] init];
        [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return _managedObjectContext;
}

- (NSManagedObjectModel *)managedObjectModel
{
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"BPData" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"BPModel.sqlite"];
    //NSLog(@"%@",storeURL);
    NSError *error = nil;
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        BPLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}

#pragma mark - Application's Documents directory

// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

//插入数据
- (void)insertCoreData:(NSArray *)productsModel
{
    NSManagedObjectContext *context = [self managedObjectContext];
    for (HomeModel *model in productsModel) {
        HomeData *data = [NSEntityDescription insertNewObjectForEntityForName:@"HomeData" inManagedObjectContext:context];
        data.title = model.title;
        data.icon = model.icon;
        data.iD = model.iD;
        NSError *error;
        if(![context save:&error])
        {
            BPLog(@"不能保存：%@",[error localizedDescription]);
        }else{
            BPLog(@"home数据保存成功");
        }
    }
}

//插入上传未完成照片
- (void)insertUnpostImage:(NSArray *)assetArry
{
    NSManagedObjectContext *context = [self managedObjectContext];
    for (ZBpostModel *model in assetArry) {
        UnpostArry *data = [NSEntityDescription insertNewObjectForEntityForName:@"UnpostArry" inManagedObjectContext:context];
        data.imageKey = model.imageKey;
        data.imageStr = model.imageStr;
        NSError *error;
        if(![context save:&error])
        {
            BPLog(@"不能保存：%@",[error localizedDescription]);
        }else{
            BPLog(@"post数据保存成功");
        }
    }
}

- (void)deleteUnpostInfo:(NSString *)imageKey
{
    NSManagedObjectContext *context = [self managedObjectContext];
    NSPredicate *predicate = [NSPredicate
                              predicateWithFormat:@"imageKey like[cd] %@",imageKey];
    
    //首先你需要建立一个request
    NSFetchRequest * request = [[NSFetchRequest alloc] init];
    [request setEntity:[NSEntityDescription entityForName:@"UnpostArry" inManagedObjectContext:context]];
    [request setPredicate:predicate];//这里相当于sqlite中的查询条件，具体格式参考苹果文档
    NSError *error = nil;
    NSArray *datas = [context executeFetchRequest:request error:&error];
    if (!error && datas && [datas count])
    {
        for (NSManagedObject *obj in datas)
        {
            [context deleteObject:obj];
        }
        if (![context save:&error])
        {
            BPLog(@"error:%@",error);
        }else{
            BPLog(@"postinfo删除成功");
        }
    }
}

- (NSMutableArray *)getAllunpostArry
{
    NSManagedObjectContext *context = [self managedObjectContext];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"UnpostArry" inManagedObjectContext:context];
    [fetchRequest setEntity:entity];
    NSError *error;
    NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
    NSMutableArray *resultArray = [NSMutableArray array];
    for (UnpostArry *info in fetchedObjects) {
        NSString *imageStr = info.imageStr;
        [resultArray addObject:imageStr];
    }
    return resultArray;
}

- (void)deleteAllpost
{
    NSManagedObjectContext *context = [self managedObjectContext];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"UnpostArry" inManagedObjectContext:context];
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setIncludesPropertyValues:NO];
    [request setEntity:entity];
    NSError *error = nil;
    NSArray *datas = [context executeFetchRequest:request error:&error];
    if (!error && datas && [datas count])
    {
        for (NSManagedObject *obj in datas)
        {
            [context deleteObject:obj];
        }
        if (![context save:&error])
        {
            BPLog(@"error:%@",error);
        }else{
            BPLog(@"postAll删除成功");
        }
    }
}

//查询
- (NSMutableArray *)homeData
{
    NSManagedObjectContext *context = [self managedObjectContext];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"HomeData" inManagedObjectContext:context];
    [fetchRequest setEntity:entity];
    NSError *error;
    NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
    NSMutableArray *resultArray = [NSMutableArray array];
    for (HomeData *info in fetchedObjects) {
        HomeModel *model = [[HomeModel alloc] init];
        model.title = info.title;
        model.icon = info.icon;
        model.iD = info.iD;
        [resultArray addObject:model];
    }
    return resultArray;
}

//删除home数据
-(void)deleteData
{
    NSManagedObjectContext *context = [self managedObjectContext];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"HomeData" inManagedObjectContext:context];
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setIncludesPropertyValues:NO];
    [request setEntity:entity];
    NSError *error = nil;
    NSArray *datas = [context executeFetchRequest:request error:&error];
    if (!error && datas && [datas count])
    {
        for (NSManagedObject *obj in datas)
        {
            [context deleteObject:obj];
        }
        if (![context save:&error])
        {
            BPLog(@"error:%@",error);
        }else{
            BPLog(@"home删除成功");
        }
    }
}
//插入list数据
- (void)insertProductListData:(NSArray *)modelArry addCID:(NSString *)cid
{
    NSManagedObjectContext *context = [self managedObjectContext];
    for (BPProducts *model in modelArry) {
        ListData *data = [NSEntityDescription insertNewObjectForEntityForName:@"ListData" inManagedObjectContext:context];
        data.title = model.title;
        data.cover = model.cover;
        data.iD = model.iD;
        data.cid = cid;
        data.price = model.price;
        data.pagetotal = model.pagetotal;
        
        NSError *error;
        if(![context save:&error])
        {
            BPLog(@"不能保存：%@",[error localizedDescription]);
        }else{
            BPLog(@"list数据保存成功");
        }
    }
}
//查询list数据
- (NSMutableArray *)productListaddCID:(NSString *)cid
{
    NSManagedObjectContext *context = [self managedObjectContext];
    NSPredicate *predicate = [NSPredicate
                              predicateWithFormat:@"cid like[cd] %@",cid];
    
    //首先你需要建立一个request
    NSFetchRequest * request = [[NSFetchRequest alloc] init];
    [request setEntity:[NSEntityDescription entityForName:@"ListData" inManagedObjectContext:context]];
    [request setPredicate:predicate];//这里相当于sqlite中的查询条件，具体格式参考苹果文档
    NSError *error = nil;
    NSArray *result = [context executeFetchRequest:request error:&error];
    NSMutableArray *resultArray = [NSMutableArray array];
    for (ListData *data in result) {
        BPProducts *model = [[BPProducts alloc] init];
        model.title = data.title;
        model.cover = data.cover;
        model.iD = data.iD;
        model.price = data.price;
        model.pagetotal = data.pagetotal;
        [resultArray addObject:model];
    }
    return resultArray;
}
//删除list数据
- (void)deleteProductListaddCID:(NSString *)cid
{
    NSManagedObjectContext *context = [self managedObjectContext];
    NSPredicate *predicate = [NSPredicate
                              predicateWithFormat:@"cid like[cd] %@",cid];
    
    //首先你需要建立一个request
    NSFetchRequest * request = [[NSFetchRequest alloc] init];
    [request setEntity:[NSEntityDescription entityForName:@"ListData" inManagedObjectContext:context]];
    [request setPredicate:predicate];//这里相当于sqlite中的查询条件，具体格式参考苹果文档
    NSError *error = nil;
    NSArray *datas = [context executeFetchRequest:request error:&error];
    if (!error && datas && [datas count])
    {
        for (NSManagedObject *obj in datas)
        {
            [context deleteObject:obj];
        }
        if (![context save:&error])
        {
            BPLog(@"error:%@",error);
        }else{
            BPLog(@"list删除成功");
        }
    }
}

//插入产品详情信息
- (void)insertProductDetail:(BPProductDetail *)productdetailModel
{
    NSManagedObjectContext *context = [self managedObjectContext];
    PagedetailData *data = [NSEntityDescription insertNewObjectForEntityForName:@"PagedetailData" inManagedObjectContext:context];
    if (![productdetailModel.pages isKindOfClass:[NSNull class]]) {
        NSData *jsondata = [NSJSONSerialization dataWithJSONObject:productdetailModel.pages options:NSJSONWritingPrettyPrinted error:nil];
        NSString *jsonString = [[NSString alloc] initWithData:jsondata
                                                     encoding:NSUTF8StringEncoding];
        
        
        data.pages = jsonString;
    }
    
    data.cover_paper = productdetailModel.cover_paper;
    data.cover_standard = productdetailModel.cover_standard;
    data.edit_w = [NSString stringWithFormat:@"%f",productdetailModel.edit_w];
    data.iD = productdetailModel.iD;
    data.page_h = [NSString stringWithFormat:@"%f",productdetailModel.page_h];
    data.page_w = [NSString stringWithFormat:@"%f",productdetailModel.page_w];
    data.page_standard = productdetailModel.page_stanard;
    
    data.page_paper = productdetailModel.page_paper;
    data.pagetotal = productdetailModel.pagetotal;
    data.promotion = productdetailModel.promotion;
    data.promotion_price = productdetailModel.promotion_price;
    data.xiaoguo = productdetailModel.xiaoguo;
    data.is_prompt = [NSString stringWithFormat:@"%d",productdetailModel.is_promot];
    data.mark_standard = productdetailModel.mark_standard;
    data.shipfee = productdetailModel.shipfee;
    data.title = productdetailModel.title;
    data.picNum = [NSNumber numberWithInt:productdetailModel.picnum];
    data.finalPrice = productdetailModel.finalPrice;
    data.price = productdetailModel.price;
    NSError *error;
    if ([data.pages rangeOfString:@"null"].length > 0 || data.pages == nil || [data.pages isKindOfClass:[NSNull class]]) {
        BPLog(@"格式不对");
    }else{
        if(![context save:&error])
        {
            BPLog(@"详情不能保存：%@",[error localizedDescription]);
        }else{
            BPLog(@"详情保存成功");
        }
    }
    
}
//查询产品详情信息
- (BPProductDetail *)returnProductDetail:(NSString*)productID
{
    NSManagedObjectContext *context = [self managedObjectContext];
    NSPredicate *predicate = [NSPredicate
                              predicateWithFormat:@"iD like[cd] %@",productID];
    
    //首先你需要建立一个request
    NSFetchRequest * request = [[NSFetchRequest alloc] init];
    [request setEntity:[NSEntityDescription entityForName:@"PagedetailData" inManagedObjectContext:context]];
    [request setPredicate:predicate];//这里相当于sqlite中的查询条件，具体格式参考苹果文档
    
    NSError *error = nil;
    NSArray *result = [context executeFetchRequest:request error:&error];//这里获取到的是一个数组，你需要取出你要更新的那个obj
    PagedetailData *detailData = [result firstObject];

    if (detailData == nil) {
        return nil;
    }else{
        BPProductDetail *detailModel = [[BPProductDetail alloc] init];
        detailModel.cover_paper = detailData.cover_paper;
        detailModel.cover_standard = detailData.cover_standard;
        detailModel.edit_w = [detailData.edit_w floatValue];
        detailModel.iD = detailData.iD;
        detailModel.page_h = [detailData.page_h floatValue];
        detailModel.page_w = [detailData.page_w floatValue];
        detailModel.page_stanard = detailData.page_standard;
        detailModel.page_paper = detailData.page_paper;
        detailModel.pagetotal = detailData.pagetotal;
        detailModel.promotion = detailData.promotion;
        detailModel.promotion_price = detailData.promotion_price;
        detailModel.xiaoguo = detailData.xiaoguo;
        detailModel.is_promot = [detailData.is_prompt intValue];
        detailModel.mark_standard = detailData.mark_standard;
        detailModel.shipfee = detailData.shipfee;
        detailModel.title = detailData.title;
        detailModel.picnum = [detailData.picNum intValue];
        detailModel.finalPrice = detailData.finalPrice;
        detailModel.price = detailData.price;
       
        NSData *jsondata = [detailData.pages dataUsingEncoding:NSUTF8StringEncoding];
        
        id jsonObject = [NSJSONSerialization JSONObjectWithData:jsondata
                                                        options:NSJSONReadingAllowFragments
                                                          error:nil];
        detailModel.pages = jsonObject;
        
        
        return detailModel;
    }
}

- (void)deleteProductDetail:(NSString *)productID
{
    NSManagedObjectContext *context = [self managedObjectContext];
    NSPredicate *predicate = [NSPredicate
                              predicateWithFormat:@"iD like[cd] %@",productID];
    
    //首先你需要建立一个request
    NSFetchRequest * request = [[NSFetchRequest alloc] init];
    [request setEntity:[NSEntityDescription entityForName:@"PagedetailData" inManagedObjectContext:context]];
    [request setPredicate:predicate];//这里相当于sqlite中的查询条件，具体格式参考苹果文档
    NSError *error = nil;
    NSArray *datas = [context executeFetchRequest:request error:&error];
    if (!error && datas && [datas count])
    {
        for (NSManagedObject *obj in datas)
        {
            [context deleteObject:obj];
        }
        if (![context save:&error])
        {
            BPLog(@"error:%@",error);
        }else{
            BPLog(@"detail删除成功");
        }
    }
}

//添加地址
- (void)insertAddress:(NSArray *)addressArry
{
    NSManagedObjectContext *context = [self managedObjectContext];
    for (BPAddressModel *model in addressArry) {
        Address *data = [NSEntityDescription insertNewObjectForEntityForName:@"Address" inManagedObjectContext:context];
        model.addressid = model.iD;
    
        data.province = model.province;
        data.city = model.city;
        data.area = model.area;
        data.addressid = [NSNumber numberWithInt:model.addressid];
        data.address = model.address;
        data.time = model.time;
        data.realname = model.realname;
        data.phone = model.phone;
        data.status = [NSNumber numberWithInt:model.status];
        data.uid = model.uid;
        NSError *error;
        if(![context save:&error])
        {
            BPLog(@"批量地址保存不成功：%@",[error localizedDescription]);
        }else{
            BPLog(@"保存成功");
        }
    }
}

//删除地址
-(void)deleteAddress:(NSString *)uid
{
    NSManagedObjectContext *context = [self managedObjectContext];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Address" inManagedObjectContext:context];
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setIncludesPropertyValues:NO];
    [request setEntity:entity];
    NSError *error = nil;
    NSArray *datas = [context executeFetchRequest:request error:&error];
    if (!error && datas && [datas count])
    {
        for (NSManagedObject *obj in datas)
        {
            [context deleteObject:obj];
        }
        if (![context save:&error])
        {
            BPLog(@"error:%@",error);
        }else{
            BPLog(@"删除所有地址成功");
        }
    }
}

- (void)deleteOneAddress:(BPAddressModel *)model
{
    NSManagedObjectContext *context = [self managedObjectContext];
    NSPredicate *predicate = [NSPredicate
                              predicateWithFormat:@"addressid == %@ && uid == %@",[NSString stringWithFormat:@"%d",model.addressid],model.uid];
    
    //首先你需要建立一个request
    NSFetchRequest * request = [[NSFetchRequest alloc] init];
    [request setEntity:[NSEntityDescription entityForName:@"Address" inManagedObjectContext:context]];
    [request setPredicate:predicate];//这里相当于sqlite中的查询条件，具体格式参考苹果文档
    NSError *error = nil;
    NSArray *result = [context executeFetchRequest:request error:&error];
    if (!error && result && [result count])
    {
        for (NSManagedObject *obj in result)
        {
            [context deleteObject:obj];
        }
        if (![context save:&error])
        {
            BPLog(@"error:%@",error);
        }else{
            BPLog(@"删除一个地址成功");
        }
    }
}

//更新一个地址
- (void)updateAddressWithAddress:(BPAddressModel *)addressMdel
{
    //1.模型转nsstring
    NSManagedObjectContext *context = [self managedObjectContext];
    NSPredicate *predicate = [NSPredicate
                              predicateWithFormat:@"addressid == %@ && uid == %@",[NSString stringWithFormat:@"%d",addressMdel.addressid],addressMdel.uid];
    
    //首先你需要建立一个request
    NSFetchRequest * request = [[NSFetchRequest alloc] init];
    [request setEntity:[NSEntityDescription entityForName:@"Address" inManagedObjectContext:context]];
    [request setPredicate:predicate];//这里相当于sqlite中的查询条件，具体格式参考苹果文档
    NSError *error = nil;
    NSArray *result = [context executeFetchRequest:request error:&error];//这里获取到的是一个数组，你需要取出你要更新的那个obj
    Address *data = [result firstObject];
    data.province = addressMdel.province;
    data.city = addressMdel.city;
    data.area = addressMdel.area;
    data.addressid = [NSNumber numberWithInt:addressMdel.addressid];
    data.address = addressMdel.address;
    data.time = addressMdel.time;
    data.realname = addressMdel.realname;
    data.phone = addressMdel.phone;
    data.status = [NSNumber numberWithInt:addressMdel.status];
    //保存
    if ([context save:&error]) {
        BPLog(@"一个地址更新成功");
    }else{
        BPLog(@"一个地址更新失败");
    }
}

//添加一个地址
- (void)insertOneAddress:(BPAddressModel *)model
{
    NSManagedObjectContext *context = [self managedObjectContext];
    Address *data = [NSEntityDescription insertNewObjectForEntityForName:@"Address" inManagedObjectContext:context];
    data.province = model.province;
    data.city = model.city;
    data.area = model.area;
    data.addressid = [NSNumber numberWithInt:model.addressid];
    data.address = model.address;
    data.time = model.time;
    data.realname = model.realname;
    data.phone = model.phone;
    data.status = [NSNumber numberWithInt:model.status];
    data.uid = model.uid;
    data.defultAddress = [NSNumber numberWithInt:model.isDefult];
    NSError *error;
    if(![context save:&error])
    {
        BPLog(@"一个地址保存不成功：%@",[error localizedDescription]);
    }else{
        BPLog(@"一个地址保存成功");
    }
}

- (NSArray *)addressAllData:(NSString *)uid
{
    NSManagedObjectContext *context = [self managedObjectContext];
    
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"uid == %@",uid];
    
    //首先你需要建立一个request
    NSFetchRequest * request = [[NSFetchRequest alloc] init];
    [request setEntity:[NSEntityDescription entityForName:@"Address" inManagedObjectContext:context]];
    [request setPredicate:predicate];//这里相当于sqlite中的查询条件，具体格式参考苹果文档
    NSError *error = nil;
    NSArray *result = [context executeFetchRequest:request error:&error];
    NSMutableArray *resultArray = [NSMutableArray array];
    for (Address *address in result) {
        BPAddressModel *addmodel = [[BPAddressModel alloc] init];
        addmodel.province = address.province;
        addmodel.city = address.city;
        addmodel.area = address.area;
        addmodel.addressid = [address.addressid intValue];
        addmodel.address = address.address;
        addmodel.time = address.time;
        addmodel.realname = address.realname;
        addmodel.phone = address.phone;
        addmodel.status = [address.status intValue];
        addmodel.uid = address.uid;
        addmodel.isDefult = [address.defultAddress intValue];
        [resultArray addObject:addmodel];
    }
    return resultArray;
}

//设置默认地址
- (void)updateDefaultAddress:(int)newDefault lastAddress:(int)lastID withuid:(NSString *)uid
{
    NSManagedObjectContext *context = [self managedObjectContext];
    NSFetchRequest * request = [[NSFetchRequest alloc] init];
    NSError *error = nil;
    [request setEntity:[NSEntityDescription entityForName:@"Address" inManagedObjectContext:context]];
    if (lastID != 0) {
        NSPredicate *predicate = [NSPredicate
                                  predicateWithFormat:@"addressid == %@ && uid == %@",[NSString stringWithFormat:@"%d",lastID],uid];

        //首先你需要建立一个request
        
        [request setPredicate:predicate];//这里相当于sqlite中的查询条件，具体格式参考苹果文档
        
        
        NSArray *result = [context executeFetchRequest:request error:&error];//这里获取到的是一个数组，你需要取出你要更新的那个obj
        Address *data = [result firstObject];
        data.defultAddress = [NSNumber numberWithInt:0];
        if ([context save:&error]) {
            //更新成功
            BPLog(@"以前地址变0");
        }
        
    }
   
    NSPredicate *predicate2 = [NSPredicate
                              predicateWithFormat:@"addressid == %@ && uid == %@",[NSString stringWithFormat:@"%d",newDefault],uid];
    
    //首先你需要建立一个request
    [request setPredicate:predicate2];//这里相当于sqlite中的查询条件，具体格式参考苹果文档
    
    NSArray *result2 = [context executeFetchRequest:request error:&error];//这里获取到的是一个数组，你需要取出你要更新的那个obj
    Address *info = [result2 firstObject];
    info.defultAddress = [NSNumber numberWithInt:1];
    //保存
    if ([context save:&error]) {
        //更新成功
        BPLog(@"新的默认地址");
    }
}

- (BPAddressModel *)getDefaultAddressWithuid:(NSString *)uid
{
    NSManagedObjectContext *context = [self managedObjectContext];
    
    NSPredicate *predicate = [NSPredicate
                              predicateWithFormat:@"defultAddress == %@ && uid == %@",[NSString stringWithFormat:@"%d",1],uid];
    //首先你需要建立一个request
    NSFetchRequest * request = [[NSFetchRequest alloc] init];
    [request setEntity:[NSEntityDescription entityForName:@"Address" inManagedObjectContext:context]];
    [request setPredicate:predicate];//这里相当于sqlite中的查询条件，具体格式参考苹果文档
    
    NSError *error = nil;
    NSArray *result = [context executeFetchRequest:request error:&error];
    Address *data = [result firstObject];
    BPAddressModel *addmodel = [[BPAddressModel alloc] init];
    addmodel.province = data.province;
    addmodel.city = data.city;
    addmodel.area = data.area;
    addmodel.addressid = [data.addressid intValue];
    addmodel.address = data.address;
    addmodel.time = data.time;
    addmodel.realname = data.realname;
    addmodel.phone = data.phone;
    return addmodel;
}

- (void)saveADIYproduct:(BPProductDetail *)Myproduct;
{
    NSManagedObjectContext *context = [self managedObjectContext];
    MyProducts *data = [NSEntityDescription insertNewObjectForEntityForName:@"MyProducts" inManagedObjectContext:context];
    [self modelTOdata:data with:Myproduct];
    NSError *error;
    if(![context save:&error])
    {
        BPLog(@"我的作品保存不成功：%@",[error localizedDescription]);
    }else{
        BPLog(@"我的作品保存成功");
    }
    for (BPProductDetailPage *page in Myproduct.pages) {
        if (page.moulds != nil) {
            page.moulds = [BPProductModel objectArrayWithKeyValuesArray:page.moulds];
        }
    }
}

- (void)updateADIYproduct:(BPProductDetail *)Myproduct
{
    NSManagedObjectContext *context = [self managedObjectContext];
    NSPredicate *predicate = [NSPredicate
                              predicateWithFormat:@"makeDate like[cd] %@",Myproduct.makeDate];
    
    //首先你需要建立一个request
    NSFetchRequest * request = [[NSFetchRequest alloc] init];
    [request setEntity:[NSEntityDescription entityForName:@"MyProducts" inManagedObjectContext:context]];
    [request setPredicate:predicate];//这里相当于sqlite中的查询条件，具体格式参考苹果文档
    NSError *error = nil;
    NSArray *result = [context executeFetchRequest:request error:&error];
    MyProducts *data = [result firstObject];
    [self modelTOdata:data with:Myproduct];
    
    if ([context save:&error]) {
        BPLog(@"作品更新成功");
    }else{
        BPLog(@"作品更新失败");
    }
    for (BPProductDetailPage *page in Myproduct.pages) {
        if (page.moulds != nil) {
            page.moulds = [BPProductModel objectArrayWithKeyValuesArray:page.moulds];
        }
    }
}

- (void)modelTOdata:(MyProducts *)data with:(BPProductDetail *)model
{
    data.cover_paper = model.cover_paper;
    data.cover_standard = model.cover_standard;
    data.edit_w = [NSNumber numberWithFloat:model.edit_w];
    data.iD = model.iD;
    data.page_h = [NSNumber numberWithFloat:model.page_h];
    data.page_w = [NSNumber numberWithFloat:model.page_w];
    data.page_standard = model.page_stanard;
    data.page_paper = model.page_paper;
    data.pagetotal = model.pagetotal;
    data.promotion = model.promotion;
    data.promotion_price = model.promotion_price;
    data.finalPrice = model.finalPrice;
    data.xiaoguo = model.xiaoguo;
    data.is_prompt = [NSString stringWithFormat:@"%d", model.is_promot];
    data.mark_standard = model.mark_standard;
    data.pages = [self arryTostr:model.pages];
    data.uid = model.uid;
    data.workID = model.workID;
    data.category = model.category;
    data.title = model.title;
    data.makeDate = model.makeDate;
    data.picnum = [NSNumber numberWithInt:model.picnum];
}

- (void)removeOneProduct:(NSString *)makeDate withUID:(NSString *)uid
{
    NSManagedObjectContext *context = [self managedObjectContext];
    NSPredicate *predicate = [NSPredicate
                              predicateWithFormat:@"makeDate == %@ && uid == %@",makeDate,uid];
    //首先你需要建立一个request
    NSFetchRequest * request = [[NSFetchRequest alloc] init];
    [request setEntity:[NSEntityDescription entityForName:@"MyProducts" inManagedObjectContext:context]];
    [request setPredicate:predicate];//这里相当于sqlite中的查询条件，具体格式参考苹果文档
    NSError *error = nil;
    NSArray *result = [context executeFetchRequest:request error:&error];
    if (!error && result && [result count])
    {
        for (NSManagedObject *obj in result)
        {
            [context deleteObject:obj];
        }
        if (![context save:&error])
        {
            BPLog(@"error:%@",error);
        }else{
            BPLog(@"删除一个作品成功");
        }
    }
}

- (void)deletOneProduct:(NSString *)workID
{
    NSManagedObjectContext *context = [self managedObjectContext];
    NSPredicate *predicate = [NSPredicate
                              predicateWithFormat:@"workID == %@",workID];
    //首先你需要建立一个request
    NSFetchRequest * request = [[NSFetchRequest alloc] init];
    [request setEntity:[NSEntityDescription entityForName:@"MyProducts" inManagedObjectContext:context]];
    [request setPredicate:predicate];//这里相当于sqlite中的查询条件，具体格式参考苹果文档
    NSError *error = nil;
    NSArray *result = [context executeFetchRequest:request error:&error];
    if (!error && result && [result count])
    {
        for (NSManagedObject *obj in result)
        {
            [context deleteObject:obj];
        }
        if (![context save:&error])
        {
            BPLog(@"error:%@",error);
        }else{
            BPLog(@"删除一个作品成功");
        }
    }
}

- (NSMutableArray *)allMyProducts:(NSString *)uid
{
    NSManagedObjectContext *context = [self managedObjectContext];
    NSPredicate *predicate = [NSPredicate
                              predicateWithFormat:@"uid like[cd] %@",uid];
    
    //首先你需要建立一个request
    NSFetchRequest * request = [[NSFetchRequest alloc] init];
    [request setEntity:[NSEntityDescription entityForName:@"MyProducts" inManagedObjectContext:context]];
    [request setPredicate:predicate];//这里相当于sqlite中的查询条件，具体格式参考苹果文档
    NSError *error = nil;
    NSArray *result = [context executeFetchRequest:request error:&error];
    
    NSMutableArray *resultArray = [NSMutableArray array];
    for (MyProducts *info in result) {
        productModel *model = [[productModel alloc] init];
        model.picture = info.xiaoguo;
        model.category = info.category;
        model.title = info.title;
        model.iD = info.workID;
        BPLog(@".....%@",model.iD);
        model.page_standard = info.cover_standard;
        model.pagetotal = info.pagetotal;
        model.product_id = info.iD;
        model.makeDate = info.makeDate;
        model.status = @"0";
        model.makeDate = info.makeDate;
        [resultArray addObject:model];
    }
    return resultArray;
}

- (NSArray *)haveProduct:(NSString *)workID{
    NSManagedObjectContext *context = [self managedObjectContext];
    NSPredicate *predicate = [NSPredicate
                              predicateWithFormat:@"workID == %@",workID];
    
    //首先你需要建立一个request
    NSFetchRequest * request = [[NSFetchRequest alloc] init];
    [request setEntity:[NSEntityDescription entityForName:@"MyProducts" inManagedObjectContext:context]];
    [request setPredicate:predicate];//这里相当于sqlite中的查询条件，具体格式参考苹果文档
    NSError *error = nil;
    NSArray *result = [context executeFetchRequest:request error:&error];
    if (result.count == 0) {
        return nil;
    }
    return result;
}

- (BPProductDetail *)getOneMyProduct:(NSString *)workID
{
    NSManagedObjectContext *context = [self managedObjectContext];
    NSPredicate *predicate = [NSPredicate
                              predicateWithFormat:@"workID == %@",workID];
    
    //首先你需要建立一个request
    NSFetchRequest * request = [[NSFetchRequest alloc] init];
    [request setEntity:[NSEntityDescription entityForName:@"MyProducts" inManagedObjectContext:context]];
    [request setPredicate:predicate];//这里相当于sqlite中的查询条件，具体格式参考苹果文档
    NSError *error = nil;
    NSArray *result = [context executeFetchRequest:request error:&error];
    MyProducts *data = [result firstObject];
    BPProductDetail *model = [[BPProductDetail alloc] init];
    
    model.cover_paper = data.cover_paper;
    model.cover_standard = data.cover_standard;
    model.edit_w = [data.edit_w floatValue];
    model.iD = data.iD;
    model.page_h = [data.page_h floatValue];
    model.page_w = [data.page_w floatValue];
    model.page_stanard = data.page_standard;
    model.page_paper = data.page_paper;
    model.pagetotal = data.pagetotal;
    model.promotion = data.promotion;
    model.promotion_price = data.promotion_price;
    model.xiaoguo = data.xiaoguo;
    model.is_promot = [data.is_prompt intValue];
    model.mark_standard = data.mark_standard;
    model.pages = [self strToArry:data.pages];
    model.title = data.title;
    model.category = data.category;
    model.workID = data.workID;
    model.makeDate = data.makeDate;
    model.finalPrice = data.finalPrice;
    model.picnum = [data.picnum intValue];
    
    return model;    
}

- (NSArray *)strToArry:(NSString *)pageStr
{
    [[NSUserDefaults standardUserDefaults] setObject:pageStr forKey:@"pageStr"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    if (pageStr == nil) {
        [MBProgressHUD showError:@"这个作品已经不能被编辑了哦!"];
        
        return nil;
    }
    else{
    NSData *jsondata = [pageStr dataUsingEncoding:NSUTF8StringEncoding];
    
    id jsonObject = [NSJSONSerialization JSONObjectWithData:jsondata
                                                    options:NSJSONReadingAllowFragments
                                                      error:nil];
    NSArray *pages = [BPProductDetailPage objectArrayWithKeyValuesArray:jsonObject];
    for (BPProductDetailPage *page in pages) {
        if (page.moulds != nil) {
            page.moulds = [BPProductModel objectArrayWithKeyValuesArray:page.moulds];
        }
    }
    
    return  pages;
    }
}

- (NSString *)arryTostr:(NSArray *)pageArry
{
    for (BPProductDetailPage *page in pageArry) {
        if (page.moulds != nil) {
            page.moulds = [BPProductModel keyValuesArrayWithObjectArray:page.moulds];
        }
    }
    pageArry = [BPProductDetailPage keyValuesArrayWithObjectArray:pageArry];
    
    NSData *jsondata = [NSJSONSerialization dataWithJSONObject:pageArry options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonString = [[NSString alloc] initWithData:jsondata
                                                 encoding:NSUTF8StringEncoding];
    
    return jsonString;
}

@end
